<?php
/**
 * Przykładowe operacje na grafice
 */

$action = isset($_GET['action']) ? $_GET['action'] : 'none';
$path = 'test.jpg';


$image = imagecreatefromjpeg($path);
$size = getimagesize($path);
$textcolor = imagecolorallocate($image, 255, 255, 255);

switch($action) {

    case 'rotate':
        $degrees = isset($_GET['deg']) ? intval($_GET['deg']) : 180;
        $image = imagerotate($image, $degrees, 0);
        break;

    case 'scale':
        $factor = isset($_GET['factor']) ? floatval($_GET['factor']) : 0.5;

        $width = (int) ($size[0] * $factor);
        $height = (int) ($size[1] * $factor);

        // GD v1
        /*$resized = imagecreate( $width, $height );
        imagecopyresized($resized, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
        */

        // GD v2
        $resized = imagecreatetruecolor($width, $height);
        imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);


        imagedestroy($image);
        $image = $resized;
        $size[0] = $width;
        $size[1] = $height;
        break;
    case 'print':

        $x = isset($_GET['x']) ? intval($_GET['x']) : $size[0]/2;
        $y = isset($_GET['y']) ? intval($_GET['y']) : $size[1]/2;
        $msg = isset($_GET['msg']) ? $_GET['msg'] : 'Wiadomość';

        draw_msg($image, $msg, $x, $y);

        break;
    case 'draw':

        $col_ellipse = imagecolorallocate($image, 255, 255, 255);
        imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

        break;

    case 'screen':
        /*
         * For this to work your Apache service must be set to 'Allow service to interact with desktop'
         * otherwise you will just get a blank image.
         * To fix this right-click My Computer, select Manage/Services and Applications/Services - find the apache service (like Apache2) and right-click,
         * select Properties - choose the Log on tab and check the 'Allow service to interact with desktop' checkbox. Restart Apache.
         */
        imagedestroy($image);
        $image = imagegrabscreen();
        break;

    default:

        break;
}

draw_msg($image, 'Action: ' . $action, 5, 5);
header('Content-type: image/jpeg;');
imagejpeg($image);

/**
 * Drukuje tekst na ekranie w zadanej pozycji
 *
 * @global type $textcolor
 * @param type $image
 * @param type $msg
 * @param type $x
 * @param type $y
 */
function draw_msg(&$image, $msg, $x = 0, $y = 0) {
    global $textcolor;

    // Funkcja imagestring przyjmuje tekst w formacie latin2
    $msg = iconv('utf-8', 'latin2', $msg);

    imagestring($image, 5, $x, $y, $msg, $textcolor);
}